package com.miracle.moa.oauth.controller;

import com.miracle.common.Result;
import com.miracle.common.StatusCode;
import com.miracle.moa.oauth.entity.AuthToken;
import com.miracle.moa.oauth.entity.LoginDto;
import com.miracle.moa.oauth.service.IAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author : miracle
 * @version : 1.0.0
 * @date : 2021/3/22 22:02
 */
@Controller
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private IAuthService authService;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    /**
     * 登录获取令牌
     *
     * @param loginDto 登录信息
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result<String> login(@Validated @RequestBody LoginDto loginDto) {
        //申请令牌 authtoken
        AuthToken authToken = authService.login(loginDto.getUsername(), loginDto.getPassword(), clientId, clientSecret);
        if (authToken == null) {
            return new Result<>(StatusCode.ERROR, "登录失败");
        }
        //返回结果
        return new Result<>(StatusCode.OK, "登录成功", authToken.getJti());
    }
}
